'use strict';
angular.module('clientApp')


/**
 * @ngdoc function
 * @name clientApp.controller:ConnectionCtrl
 * @description
 * # ConnectionCtrl
 * Controller of the clientApp
 */
.controller('ConnectionCtrl', function ($scope, $rootScope, userAPI, ngToast, $cookieStore, $location) {
	
	$scope.connexion = function() {
		if (!$cookieStore.get('user')) {		
			var user = {};
			user.name = $scope.Ilogin;
			user.password = $scope.Ipassword;
			
			userAPI.connexion(user)
			.success(function(data) {
				if (data === 'false' || data === false) {
					ngToast.create({
						content: 'Le login/mot de passe ne correspond pas',
						className: 'warning'
					});
				} else {
					$cookieStore.put('user', user.name);
					$rootScope.user = user;
					ngToast.create({
						content: 'La connection a réussie',
						className: 'success'
					});
					$location.path('/');
				}
			})
			.error(function() {
				ngToast.create({
					content: 'Erreur de communication avec le serveur',
					className: 'danger'
				});
			});
		} else {
			ngToast.create({
				content: 'Vous êtes déjà connecté',
				className: 'info'
			});
		}
	};

});
